﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using Newtonsoft.Json.Linq;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;
namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class Purchase_SupplyService : IPurchase_SupplyService
    {
        private List<Purchase_Supply> Init(bool isInit = false)
        {
            try
            {
                if (isInit)//初始化
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseSupplyCacheKey);
                var List = RedisBase.Hash_GetAll<Purchase_Supply>(StaticConstraint.PurchaseSupplyCacheKey);
                if (List != null && List.Count > 0)
                    return List;

                List = DapperDbContext.Query<Purchase_Supply>("select * from [Purchase_Supply] where Status != @Status", new { Status = Status.delete }).ToList();
                if (List.Count > 0)
                {
                    foreach (var item in List)
                        RedisBase.Hash_Set(StaticConstraint.PurchaseSupplyCacheKey, item.Id, item);
                    RedisBase.Item_SetExpire(StaticConstraint.PurchaseSupplyCacheKey, DateTime.Now.AddDays(7));
                }
                return List;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"初始化单据数据失败,isInit:{isInit},详细:{ex.ToString()}");
            }
            return new List<Purchase_Supply>();
        }

        public (int count, List<Purchase_Supply> list) GetList(string searchKey, string searchJson, int pageSize, int pageIndex)
        {
            var queryParam = JObject.Parse((searchJson == null || searchJson == "") ? "{}" : searchJson);
            int pageNum = (pageIndex - 1) * pageSize;
            var List = Init().OrderBy(x => x.SupplyNo).ThenBy(x => x.Supplier).ToList();
            if (!searchKey.IsEmpty())
            {
                List = List.FindAll(x => (x.Supplier.Contains(searchKey) || x.SupplyNo.Contains(searchKey) || x.ContactPerson.Contains(searchKey)));
            }
            if (!queryParam["beginTime"].IsEmpty())
            {
                List = List.FindAll(x => x.CreateTime >= Convert.ToDateTime(queryParam["beginTime"]));
            }
            if (!queryParam["endTime"].IsEmpty())
            {
                List = List.FindAll(x => x.CreateTime <= Convert.ToDateTime(queryParam["endTime"]));
            }
            if (!queryParam["SupplyNo"].IsEmpty())
            {
                List = List.FindAll(x => x.SupplyNo.Contains(queryParam["SupplyNo"].ToString()));
            }
            if (!queryParam["Supplier"].IsEmpty())
            {
                List = List.FindAll(x => x.Supplier.Contains(queryParam["Supplier"].ToString()));
            }
            if (!queryParam["ContactPerson"].IsEmpty())
            {
                List = List.FindAll(x => x.ContactPerson.Contains(queryParam["ContactPerson"].ToString()));
            }

            var ParamList = List.Skip(pageNum).Take(pageSize).ToList();
            return (List.Count, ParamList);
        }
        public int Save(Purchase_Supply ent, UserCache user)
        {
            IDbModelService<Purchase_Supply> db = new DbModelService<Purchase_Supply>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    if (ent.Id == 0)
                    {
                        ent.Create(user);
                        var noteid = db.InsertOne(ent, conn, transaction);
                        ent.Id = noteid;

                        RedisBase.Hash_Set(StaticConstraint.PurchaseSupplyCacheKey, noteid, ent);
                        transaction.Commit();
                        return noteid;
                    }
                    else
                    {
                        ent.Modify(user);
                        db.UpdateById(ent, conn, transaction);
                        transaction.Commit();
                        if (ent != null)//更新线索缓存
                        {

                            RedisBase.Hash_Remove(StaticConstraint.PurchaseSupplyCacheKey, ent.Id.ToString());
                            RedisBase.Hash_Set(StaticConstraint.PurchaseSupplyCacheKey, ent.Id, ent);
                        }
                        return ent.Id;
                    }

                }
            }
            catch (Exception ex)
            {

                transaction.Rollback();
                return -1;
            }
        }
        public int Del(List<int> Ids, UserCache user)
        {
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    string sql = "UPDATE [dbo].[Purchase_Supply] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id in @Id";
                    int delcount = conn.Execute(sql, new { Status = Status.delete, LastUpdateUser = user.UserId, LastUpdateTime = DateTime.Now, Id = Ids });
                    if (delcount > 0)
                    {
                        foreach (var id in Ids)
                        {
                            RedisBase.Hash_Remove(StaticConstraint.PurchaseSupplyCacheKey, id.ToString());
                        }
                    }
                    return delcount;
                }

            }
            catch (Exception ex)
            {

                return -1;
            }

        }
        public int FindMaxNo(int cityId, int Id)
        {
            string sql = string.Format("select max(SupplyNo) from Purchase_Supply where City={0} ", cityId);
            if (Id != 0)
            {
                sql = sql + string.Format(" and Id!={0} ", Id);
            }
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    string MaxSupplyNo = conn.ExecuteScalar(sql).ToString();

                    int maxNo = Convert.ToInt32(MaxSupplyNo.Split('-')[2]) + 1;

                    return maxNo;
                }
            }
            catch
            {
                return -1;
            }
        }
        public List<Purchase_Supply> GetAllList()
        {
            return Init().ToList();
        }
    }
}
